import cgi
import os
import xml.etree.cElementTree as etree
import logging

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app

from db_model import User
from db_model import Envy
from db_model import Product
from db_model import Review

# Third party imports
import appjson
import oauth    
from Crypto.PublicKey import RSA
from Crypto.Util import number

logging.getLogger().setLevel(logging.DEBUG)

class EnvyServer(webapp.RequestHandler):
  def get(self):
    userid = self.request.get("userid")
    ownerUser = User.gql('WHERE id=:userid', userid=userid).fetch(100)
    userkeys =[]
    for user in ownerUser:
      userkeys.append(user.key())
    envies = []
    if(len(ownerUser)>0):
      envies = Envy.gql('where user in :userkeys order by updatedDate DESC', userkeys=userkeys)
      #envies = ownerUser[0].envies
    results = []
    for envy in envies:
      envyResult = {'envy_id':envy.key().id()
                    ,'name':envy.product.name
                    ,'type':envy.product.type
                    ,'product_id':envy.product.key().id()
                    ,'siteName':envy.product.siteName
                    ,'siteSku':envy.product.siteSku
                    ,'brand':envy.product.brand
                    ,'model':envy.product.model
                    ,'url':envy.product.url
                    ,'imageurl':envy.product.imageurl
                    ,'latestPrice':envy.product.latestPrice
                    ,'latestPriceDate':str(envy.product.latestPriceDate)
                    ,'envy':envy.envy
                    ,'priceEnvy':envy.priceEnvy
                    ,'owningStatus':envy.owningStatus
                    ,'lastAction':envy.lastAction
                    ,'createdDate':str(envy.createdDate)
                    ,'updatedDate':str(envy.updatedDate)}
      results.append(envyResult)
    
    self.response.out.write(appjson.write(results))
    
class ActivityServer(webapp.RequestHandler):
  def get(self):
    idsStr = self.request.get("ids")
    users = User.all().fetch(10)
    userkeys =[]
    for user in users:
      if(idsStr.find(user.id) != -1):
        userkeys.append(user.key())
    envies = []
    if(len(userkeys)>0):
      envies = Envy.gql('where user in :userkeys order by updatedDate DESC', userkeys=userkeys)
      #envies = ownerUser[0].envies
    results = []
    for envy in envies:
      envyResult = {'person_id':envy.user.id
                    ,'name':envy.product.name
                    ,'type':envy.product.type
                    ,'product_id':envy.product.key().id()
                    ,'siteName':envy.product.siteName
                    ,'siteSku':envy.product.siteSku
                    ,'brand':envy.product.brand
                    ,'model':envy.product.model
                    ,'url':envy.product.url
                    ,'imageurl':envy.product.imageurl
                    ,'latestPrice':envy.product.latestPrice
                    ,'latestPriceDate':str(envy.product.latestPriceDate)
                    ,'envy':envy.envy
                    ,'priceEnvy':envy.priceEnvy
                    ,'owningStatus':envy.owningStatus
                    ,'lastAction':envy.lastAction
                    ,'createdDate':str(envy.createdDate)
                    ,'updatedDate':str(envy.updatedDate)}
      results.append(envyResult)
    
    self.response.out.write(appjson.write(results))

class UpdateServer(webapp.RequestHandler):
  def get(self):
    userid = self.request.get("userid")
    ownerUser = User.gql('WHERE id=:userid', userid=userid).fetch(10)
    userkeys =[]
    for user in ownerUser:
      userkeys.append(user.key())
    envies = []
    if(len(ownerUser)>0):
      envies = Envy.gql('where user in :userkeys and posted = FALSE order by updatedDate DESC', userkeys=userkeys)
      #envies = ownerUser[0].envies
    results = []
    for envy in envies:
      updateStr = ' added %s to their %s list.'  % (envy.product.name
                                 , envy.owningStatus)
      imageStr = '<img src="%s" width=50 height=50/>' % envy.product.imageurl
      logging.debug(imageStr)
      results.append({'title':updateStr, 'image':imageStr})
      envy.posted = True
      envy.put()
    
    self.response.out.write(appjson.write(results))

class Seed(webapp.RequestHandler):
  def get(self):
    #self.seedUser()
    product = self.seedProduct()
    user = self.seedUser("Jack", "2153604150334753971")
    self.seedEnvy(user, product)
    user = self.seedUser("Sachin", "9653917649753444145")
    self.seedEnvy(user, product)
    user = self.seedUser("Stacie", "4069271480532865562")
    self.seedEnvy(user, product)
    user = self.seedUser("Van", "16774158048318259517")
    self.seedEnvy(user, product)
    user = self.seedUser("Akshar", "17971805101816933849")
    self.seedEnvy(user, product)
    print 'good'
    
  def seedUser(self, name, id):
    user = User(name=name, id=id)
    user.put()
    return user
    
  def seedProduct(self):
    product = Product(name="MacBook Air"
                      ,siteName="BestBuy"
                      ,siteSku="macbookair"
                      ,type="notebook"
                      ,brand="Apple"
                      ,model="MacBook")
    product.put()
    return product

  def seedEnvy(self, user, product):
    envy = Envy(user=user
                ,product=product
                ,envy="Love it")
    envy.put()